package com.example.aijava.qiniuyun;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
public class QiniuAiService {

    @Autowired
    private QiniuAiConfig qiniuAiConfig;

    @Autowired
    private RestTemplate restTemplate;

    public String sendChatRequest(String userMessage) {
        // 构建对话消息
        List<Message> messages = new ArrayList<>();
        messages.add(new Message("system", "You are a helpful assistant."));
        messages.add(new Message("user", userMessage));

        // 构建请求体
        QiniuChatRequest request = new QiniuChatRequest();
        request.setStream(false);
        request.setModel(qiniuAiConfig.getModel());
        request.setMessages(messages);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + qiniuAiConfig.getApiKey());

        // 发送请求
        HttpEntity<QiniuChatRequest> entity = new HttpEntity<>(request, headers);
        ResponseEntity<QiniuChatResponse> response = restTemplate.exchange(
                qiniuAiConfig.getApiUrl(),
                HttpMethod.POST,
                entity,
                QiniuChatResponse.class
        );

        // 解析响应
        if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
            List<QiniuChatResponse.Choice> choices = response.getBody().getChoices();
            if (!choices.isEmpty()) {
                return choices.get(0).getMessage().getContent();
            }
        }
        return "请求失败，状态码：" + response.getStatusCodeValue();
    }
}